﻿using System;
using System.Collections.Generic;
using System.Linq;
using NBlog.Web.Application.Service.Entity;
using NBlog.Web.Application.Storage;

namespace NBlog.Web.Application.Service.Internal
{
    public interface IStatsService
    {
        void AddView(string slug);
        List<Stats> GetList();
    }

    public class StatsService : IStatsService
    {
        private readonly IRepository _repository;

        public StatsService(IRepository repository)
        {
            _repository = repository;
        }

        public void AddView(string slug)
        {
            if (string.IsNullOrWhiteSpace(slug))
                throw new ArgumentNullException("slug");

            var stats = new Stats();
            var isUpdate = _repository.Exists<Stats>(slug);
            if (isUpdate)
            {
                stats = _repository.Single<Stats>(slug);
                stats.Views += 1;
            }
            else
            {
                stats.Slug = slug;
                stats.Views = 1;
            }

            _repository.Save(stats);
        }

        public List<Stats> GetList()
        {
            return _repository.All<Stats>().ToList();
        }
    }
}